package com.spring.theory.boot.event;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * TestEvent1
 * 事件监听器第一种实现
 *
 * @author H
 * @version 1.0
 * @date 2024-02-01 17:25
 */
@Slf4j
@Configuration
public class TestEvent1 {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestEvent1.class);
        context.getBean(MyService.class).doBusiness();
        context.close();
    }

    static class MyEvent extends ApplicationEvent {
        public MyEvent(Object source) {
            super(source);
        }
    }

    @Component
    static class MyService {
        @Resource
        private ApplicationEventPublisher eventPublisher;

        public void doBusiness() {
            log.info("doBusiness 主线");
            eventPublisher.publishEvent(new MyEvent("发送事件"));
        }
    }

    @Component
    static class SmsService implements ApplicationListener<MyEvent> {
        @Override
        public void onApplicationEvent(MyEvent event) {
            log.info("SmsService 发送短信");
        }
    }

    @Component
    static class EmailService implements ApplicationListener<MyEvent> {
        @Override
        public void onApplicationEvent(MyEvent event) {
            log.info("EmailService 发送邮件");
        }
    }


}
